import java.util.HashMap;
import java.util.Map;

public class Code_19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head==null){
            return null;
        }
        ListNode node =head;
        Map<Integer,ListNode> map =new HashMap<>();
        int length = 0;
        while (node!=null){
            map.put(length,node);
            length++;
            node=node.next;
        }
        int index = length-n;
        ListNode node2 = map.get(index);
        if (length==1){
            return null;
        }else if (n==length){
            head =node2.next;
            node2.next=null;
        }else {
            ListNode node1 = map.get(index-1);
            node1.next = node2.next;
            node2.next=null;
        }
        return head;
    }
}
